package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.errorprone.annotations.Var;
import com.zhentao.mapper.ApUserMapper;
import com.zhentao.model.dtos.LoginDto;
import com.zhentao.model.dtos.ResponseResult;
import com.zhentao.model.enums.AppHttpCodeEnum;
import com.zhentao.model.pojo.ApUser;
import com.zhentao.service.ApUserService;
import com.zhentao.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl implements ApUserService {
    @Autowired
    private ApUserMapper apUserMapper;


    @Override
    public ResponseResult login(LoginDto loginDto) {
        //判断账号是否存在
        if(StringUtils.isNotBlank(loginDto.getPhone()) && StringUtils.isNotBlank(loginDto.getPassword())){
            QueryWrapper<ApUser> apUserQueryWrapper = new QueryWrapper<>();
            apUserQueryWrapper.lambda().eq(ApUser::getPhone, loginDto.getPhone());
            ApUser apUser = apUserMapper.selectOne(apUserQueryWrapper);
            //账号判断
            if(apUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "账号不存在!");
            }
            //密码校验
            //盐
            String salt = apUser.getSalt();
            String password = DigestUtils.md5DigestAsHex((loginDto.getPassword() + salt).getBytes());
            if(!password.equals(apUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
            }
            //账号密码都正确  通过jwt加密成token  将token和用户信息给前端
            String token = AppJwtUtil.getToken(apUser.getId().longValue());

            Map<String,Object> map = new HashMap<>();
            map.put("token", token);
            apUser.setPassword(null);//密码不给前端
            apUser.setSalt(null);//盐也不传

            map.put("user", apUser);

            return ResponseResult.okResult(map);
        }else {
            //游客登录  游客默认id为0
            String token = AppJwtUtil.getToken(0L);

            Map<String,Object> map = new HashMap<>();
            map.put("token", token);
            return ResponseResult.okResult(map);
        }

    }
}
